from django.utils.deprecation import MiddlewareMixin
from timeholder import models
from django.conf import settings
from django.shortcuts import redirect
from datetime import datetime,timedelta

class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        """如果用户已经登录，则request中赋值"""
        # 获取session中的username
        user_name = request.session.get('username')
        request.cur_date=request.session.get('cur_date')
        if not request.cur_date:
            request.cur_date=datetime.strftime(datetime.now(),"%Y-%m-%d")
        # print(user_name)
        # 获取用户名对应的对象user_obj
        user_obj = models.UserInfo.objects.filter(username=user_name).first()
        # 赋值给request中存储，方便后续读取
        request.user_obj = user_obj

        #为request添加一个日期的列表：
        thisDay=datetime.now()
        days_list=[]
        for i in range(7):
            theDay=thisDay-timedelta(days=i)
            day_str=str(theDay.year)+"-"+str(theDay.month)+"-"+str(theDay.day)
            days_list.append(day_str)
        request.days_list = days_list
        request.newDate=str(thisDay.year)+"-"+str(thisDay.month)+"-"+str(thisDay.day)
        # 如果在白名单中，则通过
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        # 如果没有登录且不在白名单中，则跳转到登录页面
       # if not user_obj:
          #  return redirect('/login/')
